package com.alili_tv.system.intercepter;

import com.alili_tv.system.common.BaseContext;
import com.alili_tv.system.common.LoginRequired;
import com.alili_tv.system.common.SessionCache;
import com.alili_tv.system.exception.BusinessException;
import com.alili_tv.system.exception.NotLoginException;
import com.alili_tv.system.utils.CacheUtils;
import com.alili_tv.system.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * 拦截器：拦截到有LoginRequired注解的接口方法时，判断用户是否登录
 */
public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod handlerMethod)) return true;

        // 方法注解级拦截器
        Method method = handlerMethod.getMethod();

//        // 获取缓存数据
//        HttpSession session = request.getSession();
//        SessionCache cacheInfo = (SessionCache) session.getAttribute("AUTHORITY");
        // 获取token
        String token = request.getHeader("token");
        Long userId = JwtUtils.getVal(token);
        if (JwtUtils.validate(token)) {
            BaseContext.setCurrentId(userId);
        } else {
            BaseContext.setCurrentId(null);
        }

        // 判断接口是否需要登录
        LoginRequired annotation = method.getAnnotation(LoginRequired.class);
        // 方法有 @LoginRequired 注解限制，需要认证
        if (annotation != null) {
            if (userId == null)
                throw new NotLoginException("登录享受更多特权");
        }

//        if (cacheInfo != null) {
//            // 设置LocalThread当前用户id
//            BaseContext.setCurrentId(cacheInfo.getUserId());
//            // 更新登录缓存
//            SessionCache.refresh(cacheInfo, session);
//        }

        // 方法没有权限限制直接通过
        return true;
    }
}
